package com.aabte.nettyleran.netty.http.xml.entity;

import org.jibx.runtime.*;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/14
 */
public class OrderXmlSerialTest {

    private IBindingFactory factory = null;
    private StringWriter writer = null;
    private StringReader reader = null;
    public static final String CHARSET_NAME = StandardCharsets.UTF_8.toString();

    public static void main(String[] args) throws JiBXException, IOException {
        OrderXmlSerialTest test = new OrderXmlSerialTest();
        Order order = OrderFactory.createOrder(1L);
        String xmlBody = test.encode2Xml(order);
        System.out.println("xmlBody = " + xmlBody);
        Order order1 = test.decode2Order(xmlBody);
        System.out.println("order1 = " + order1);
    }

    private String encode2Xml(Order order) throws JiBXException, IOException {
        factory = BindingDirectory.getFactory(Order.class);
        writer = new StringWriter();
        IMarshallingContext mctx = factory.createMarshallingContext();
        mctx.setIndent(2);
        mctx.marshalDocument(order, CHARSET_NAME, null, writer);
        String xmlStr = writer.toString();
        writer.close();
        return xmlStr;
    }

    private Order decode2Order(String xmlBody) throws JiBXException {
        reader = new StringReader(xmlBody);
        IUnmarshallingContext uctx = factory.createUnmarshallingContext();
        Order order = (Order) uctx.unmarshalDocument(reader);
        return order;
    }

}
